package com.scalar.chiptrack.adaptor.dongbu;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import java.io.BufferedInputStream;
import java.util.Calendar;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;


/**
 * User: ChandraSekhar
 * Date: Aug 2, 2007
 * Time: 2:58:32 PM
 */
public class DongbuAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_HTTP           = "http";
    private static final String HOST                    = "yourfab.dongbuhitek.com";
    private static final String GET_REAL_WIP_STATUS     = "/src/wip/Current_WIP_Tracking_V3.asp";
    private static final String GET_SHIP_STATUS         = "/src/ship/Monthly_Shipping_Summary_V3.asp";
    private static final String LOG_OUT                 = "/src/login/login.asp?mode=logout";
    private static final int DEFAULT_PORT               = 80;

    public static final String FILE_NAME_SHIP_STATUS        = "DONGBU_SHIP_STATUS";
    public static final String FILE_NAME_WIP_STATUS         = "DONGBU_WIP_STATUS";
    public static final String ADAPTOR_NAME                 = "DONGBU_FAB";

    private String m_dataOutputDir  = null;
    private Logger m_adaptorLogger  = null;
    private String m_username       = null;
    private String m_password       = null;
    private String m_custName       = null;
    private int    m_adaptor_id     = -1;

    public DongbuAdaptor() throws Exception
    {
       try
        {
           VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_DONGBU, WIP_TYPE_FAB );

            if( vendorAdaptor == null )
            {
                log( "ERROR!! ERROR!! ERROR!! Exception while loading DONGBU Adaptor Username, Password details from database" );
                throw new ScalarException( "Exception while loading DONGBU Adaptor Username, Password details from database" );
            }

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();
            m_custName      = vendorAdaptor.getCustomerId().trim().toUpperCase();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir , VENDOR_NAME_DONGBU);
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading DONGBU Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading DONGBU Adaptor Username, Password details from database" );
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new DongbuAdaptor().execute();
    }

    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            // Step 1
            // prints the version of Adaptor
            AdaptorUtils.printHeader(VENDOR_NAME_DONGBU, CONSTANT_ADAPTOR );

            // Step 2
            // removes the old files out side done directory
           AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);


            HTTPConnection connection = login( HOST, DEFAULT_PORT, m_username, m_password );

            if ( connection != null )
            {
                BufferedInputStream bfReader = null;

                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipStatusReport( connection );
                
                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Lot Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip Status Sheet" );
                    throw new ScalarException( "Could not create response object of Wip Status Sheet" );
                }
            
                // For DownLoding the Shipment Information
                HTTPResponse rsp1 = requestShippingReport( connection );

                if( rsp1 != null )
                {
                    bfReader = new BufferedInputStream( rsp1.getInputStream()  );
                    if( bfReader != null )
                    {
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_SHIP_STATUS, FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Dynamic Ship Status Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Ship Status Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Ship Status Sheet" );
                    throw new ScalarException( "Could not create response object of Ship Status Sheet" );
                }

                // Logging out from DONGBU WEB SITE
                logout( connection );

                System.out.println( "\nDone..." );
                log( "\nDone..." );
                bfReader = null;
            }
            else
            {
                log( "Could not able to get the Connection to web site" );
                throw new ScalarException( "Could not able to get the Connection to web site" );
            }
        }
        catch(Exception e )
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
            System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    private HTTPConnection login( String host, int port, String username, String password ) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse    rsp = null;

        HTTPConnection conn = new HTTPConnection( PROTOCOL_HTTP, host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        NVPair defaultHeaders[] = new NVPair[ 8 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "*/*" );
        defaultHeaders[ 1 ] = new NVPair( "Referer", "http://" + host );
        defaultHeaders[ 2 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 3 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 4 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 5 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" );
        defaultHeaders[ 6 ] = new NVPair( "Host", host );
        defaultHeaders[ 7 ] = new NVPair( "Pragma", "no-cache" );

        conn.setDefaultHeaders( defaultHeaders );

        //rsp  = conn.Get( "/login.asp" );

        NVPair[] formData = new NVPair[ 5 ];
        formData[ 0 ] = new NVPair( "mode", "login" );
        formData[ 1 ] = new NVPair( "id", username );
        formData[ 2 ] = new NVPair( "password", password );
        formData[ 3 ] = new NVPair( "browser_name", "Microsoft Internet Explorer" );
        formData[ 4 ] = new NVPair( "date", "" );
        System.out.println( "\nTrying to Logging in......" );
        log( "\nTrying to Logging in......" );

        rsp  = conn.Post( "/src/login/login.asp", formData );

        log("rsp.getEffectiveURI() = " + rsp.getEffectiveURI() );
        while (rsp.getInputStream().read(data) != -1)
        {
           //System.out.println(new String(data));
        }
        log( "Done." );
        return conn;
    }
    
    private HTTPResponse requestWipStatusReport(HTTPConnection conn) throws Exception
    {
        System.out.println("Submitting request for wip Report.......");

        NVPair[] formData = new NVPair[6];

        formData[0]  = new NVPair("ddl_val2", m_custName+",");
        formData[1]  = new NVPair("ddl_val3", "ALL,");
        formData[2]  = new NVPair("ddl_val4", "ALL,");
        formData[3]  = new NVPair("ddl_val1", "ALL,");
        formData[4]  = new NVPair("ddl_val5", "Customer,");
        formData[5]  = new NVPair("mode", "Excel");

        HTTPResponse rsp = conn.Post(GET_REAL_WIP_STATUS, formData);

        System.out.println("\tDownloading Wip Report........... ");
        log("\n Downloading Wip Report.... ");

        return rsp;
    }
    private HTTPResponse requestShippingReport( HTTPConnection conn ) throws Exception
    {
        System.out.println("Submitting request for Ship Report.......");

        Calendar beginCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        beginCal.add( Calendar.DAY_OF_MONTH, -15 );

        String beginYear = beginCal.get( Calendar.YEAR ) + "";
        String beginMonth = ( beginCal.get( Calendar.MONTH ) + 1 ) + "";
        if ( beginMonth.length() == 1 )
        {
            beginMonth = "0" + beginMonth;
        }

        String beginDay = beginCal.get( Calendar.DAY_OF_MONTH ) + "";
        if ( beginDay.length() == 1 )
        {
            beginDay = "0" + beginDay;
        }

        String endYear = endCal.get( Calendar.YEAR ) + "";
        String endMonth = ( endCal.get( Calendar.MONTH ) + 1 ) + "";
        if ( endMonth.length() == 1 )
        {
            endMonth = "0" + endMonth;
        }

        String endDay = endCal.get( Calendar.DAY_OF_MONTH ) + "";
        if ( endDay.length() == 1 )
        {
            endDay = "0" + endDay;
        }
        //System.out.println( "Begining date = " + beginYear + "/" + beginMonth + "/" + beginDay );
        //System.out.println( "End date = " + endYear + "/" + endMonth + "/" + endDay );
        NVPair[] formData = new NVPair[18];

        formData[0]  = new NVPair("ddl_val2", m_custName +",");
        formData[1]  = new NVPair("ddl_val3", "ALL,");
        formData[2]  = new NVPair("ddl_val4", "ALL,");
        formData[3]  = new NVPair("ddl_val1", "ALL,");
        formData[4]  = new NVPair("ddl_val5", "Customer,");
        formData[5]  = new NVPair("mode", "Excel");
        formData[6]  = new NVPair("from1_date", beginYear+",");
        formData[7]  = new NVPair("from2_date", beginMonth+",");
        formData[8]  = new NVPair("from3_date", beginDay+",");
        formData[9]  = new NVPair("to1_date", endYear+",");
        formData[10]  = new NVPair("to2_date", endMonth+",");
        formData[11]  = new NVPair("to3_date", endDay+",");
        formData[12]  = new NVPair("from1", beginYear);
        formData[13]  = new NVPair("from2", beginMonth);
        formData[14]  = new NVPair("from3", beginDay);
        formData[15]  = new NVPair("to1", endYear);
        formData[16]  = new NVPair("to2", endMonth);
        formData[17]  = new NVPair("to3", endDay);

        HTTPResponse rsp = conn.Post(GET_SHIP_STATUS, formData);

        System.out.println("\tDownloading Ship Report........... ");
        log("\n Downloading Ship Report.... ");

        return rsp;
    }
    private void logout( HTTPConnection conn ) throws Exception
    {
        try
        {
            System.out.print( "\n Logging out... " );
            log( "\n Logging out... " );
            HTTPResponse rsp = conn.Get( LOG_OUT );
            System.out.println( "Successfully logged out from DONGBU Site" );
            log( "Successfully logged out from DONGBU Site" );

            conn = null;
            rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From DONGBU Site" + ignore);
            throw ignore;
        }
    }
       
    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }

}
